package com.mk.cloud.pt.service.app;

import com.mk.cloud.common.domain.PCoconfig;
import com.mk.cloud.common.domain.PCompany;
import com.mk.cloud.common.interceptor.header.HeaderService;
import org.osgl.util.S;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

public class PCompanyService extends HeaderService{

    @Inject
    private PCompany.Mapper pCompanyMapper;
    @Inject
    private PCoconfig.Mapper pCoconfigMapper;

    private static Map<String,PCompany> map;

    //通过appid查询
    public PCompany getCompanyByAppid(String appid){
        if(map==null){
            map = new HashMap<>();
        }
        if(map.get(appid)==null){
            PCompany company = new PCompany();
            company.setAppid(appid);
            PCompany pCompany = pCompanyMapper.templateOne(company);
            getCoconfig(appid, pCompany);
        }
        return map.get(appid);
    }

    //通过coid查询
    public PCompany getCompanyByCoid(String coid){
        if(map==null){
            map = new HashMap<>();
        }
        if(map.get(coid)==null){
            PCompany pCompany = pCompanyMapper.single(coid);
            getCoconfig(coid, pCompany);
        }
        return map.get(coid);
    }

    /**
     * 根据coid清理map中缓存的企业信息
     * @param coid
     */
    public void clearCashByCoid(String coid){
        if(map!=null){
            PCompany pCompany = pCompanyMapper.single(coid);
            map.remove(coid);
            if(pCompany!=null&& S.isNotBlank(pCompany.getAppid())){
                map.remove(pCompany.getAppid());
            }
        }
    }


    //查询企业相关配置
    private void getCoconfig(String coid, PCompany pCompany) {
        if(pCompany!=null){
            PCoconfig coconfig = pCoconfigMapper.single(pCompany.getCoid());
            if(coconfig==null){
                coconfig = new PCoconfig();
            }
            pCompany.setPCoconfig(coconfig);
            map.put(coid,pCompany);
            map.put(pCompany.getCoid(),pCompany);
        }
    }

}
